//
//  OrderViewController.m
//  Japanese+
//
//  Created by Jame on 15/10/20.
//  Copyright © 2015年 SSIC. All rights reserved.
//

#import "OrderViewController.h"
#import "NewCell.h"
#import "OrderCell.h"

#import "OrderModel.h"

@interface OrderViewController () <UITableViewDataSource,UITableViewDelegate,MBProgressHUDDelegate,UIAlertViewDelegate>

@end

@implementation OrderViewController
{
    UIView *_chooseView;
    UITableView *_tableView;
    NSMutableDictionary *_checkDictionary;
    MBProgressHUD *_HUD;
    
    MemberModel *_memberModel;
    TeacherModel *_teacherModel;
    
    OrderModel *_orderModel;
    NSString *_lat;
    NSString *_lng;
    NSMutableArray *_dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatNavigationBarWithImage:nil title:@"抢单"];
    
    [self creatChooseView];
    [self creatTableView];
}


- (void)viewWillAppear:(BOOL)animated
{
    [self loadUserInfo];
    UIButton *button = (UIButton *)[self.view viewWithTag:105];
    [self chooseClick:button];
}


- (void)loadUserInfo
{
    UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
    [userInfo loadUserInfoFromSanbox];
    _memberModel = userInfo.memberModel;
    _teacherModel = userInfo.teacherModel;
    _lat = userInfo.lat;
    _lng = userInfo.lng;
}


- (void)creatChooseView
{
    _chooseView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, ECSCREEN_W, 40)];
    _chooseView.backgroundColor = ECCOLOR(255, 255, 255, 1);
    [self.view addSubview:_chooseView];
    
    
    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
    newButton.tag = 105;
    newButton.frame = CGRectMake(0, 0, ECSCREEN_W/2, 40);
    [newButton setTitle:@"新生源" forState:UIControlStateNormal];
    [newButton setTitleColor:ECCOLOR(0, 0, 0, 1) forState:UIControlStateNormal];
    newButton.titleLabel.font = [UIFont systemFontOfSize:15.f];
    [newButton setImage:ECIMAGENAME(@"order_down.png") forState:UIControlStateNormal];
    newButton.imageEdgeInsets = UIEdgeInsetsMake(0, 140, 0, 0);
    [newButton addTarget:self action:@selector(chooseClick:) forControlEvents:UIControlEventTouchUpInside];
    [_chooseView addSubview:newButton];
    
    UIView *speraLine = [[UIView alloc] initWithFrame:CGRectMake(ECSCREEN_W/2, 5, 1, 30)];
    speraLine.backgroundColor = ECCOLOR(212, 50, 47, .3f);
    [_chooseView addSubview:speraLine];
    
    
    UIButton *orderButton = [UIButton buttonWithType:UIButtonTypeCustom];
    orderButton.tag = 106;
    orderButton.frame = CGRectMake(ECSCREEN_W/2+1, 0, ECSCREEN_W/2, 40);
    [orderButton setTitle:@"抢单" forState:UIControlStateNormal];
    [orderButton setTitleColor:ECCOLOR(0, 0, 0, 1) forState:UIControlStateNormal];
    orderButton.titleLabel.font = [UIFont systemFontOfSize:15.f];
    [orderButton setImage:ECIMAGENAME(@"order_down.png") forState:UIControlStateNormal];
    orderButton.imageEdgeInsets = UIEdgeInsetsMake(0, 140, 0, 0);
    [orderButton addTarget:self action:@selector(chooseClick:) forControlEvents:UIControlEventTouchUpInside];
    [_chooseView addSubview:orderButton];
}



- (void)chooseClick:(UIButton *)button
{
    UIButton *newButton = (UIButton *)[self.view viewWithTag:105];
    UIButton *orderButton = (UIButton *)[self.view viewWithTag:106];
    
    switch (button.tag) {
        case 105:
        {
            newButton.selected = YES;
            orderButton.selected = NO;
            [newButton setTitleColor:NAVC_COLOR forState:UIControlStateNormal];
            [orderButton setTitleColor:ECCOLOR(0, 0, 0, 1) forState:UIControlStateNormal];
            [newButton setImage:ECIMAGENAME(@"order_down.png") forState:UIControlStateNormal];
            [orderButton setImage:ECIMAGENAME(@"order_up.png") forState:UIControlStateNormal];
            if (_lat.length >0 &&_lng.length > 0) {
                [self creatFirstHttpRequest];
            }
        }
            break;
        case 106:
        {
            newButton.selected = NO;
            orderButton.selected = YES;
            [newButton setTitleColor:ECCOLOR(0, 0, 0, 1) forState:UIControlStateNormal];
            [orderButton setTitleColor:NAVC_COLOR forState:UIControlStateNormal];
            [newButton setImage:ECIMAGENAME(@"order_up.png") forState:UIControlStateNormal];
            [orderButton setImage:ECIMAGENAME(@"order_down.png") forState:UIControlStateNormal];
            if (_lat.length >0 &&_lng.length > 0) {
                [self creatSecondHttpRequest];
            }
        }
            break;

            
        default:
            break;
    }
}


- (void)creatFirstHttpRequest
{
    NSDictionary *param = @{
                            @"promulgator_Id":_memberModel.member_Id,
                            @"promulgator_mark":@"2",
                            @"status":@"2",
                            @"lng":_lng,
                            @"lat":_lat,
                            };
    
    [[HttpManager defaultManager]postRequestToUrl:RequestURL(COURSE) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            [OrderModel setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data":@"OrderData",
                         };
            }];
            
            if (_dataArray) {
                [_dataArray removeAllObjects];
            }else{
                _dataArray = [[NSMutableArray alloc] init];
            }
            _orderModel = [[OrderModel alloc] init];
            _orderModel = [OrderModel objectWithKeyValues:result];
            [_dataArray addObjectsFromArray:_orderModel.data];
            [_tableView reloadData];
        }
    }];
}


- (void)creatSecondHttpRequest
{
    NSDictionary *param = @{
                             @"promulgator_mark":@"2",
                             @"status":@"1",
                             @"lat":_lat,
                             @"lng":_lng,
                             };
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(COURSE) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            [OrderModel setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"data":@"OrderData",
                         };
            }];
            
            if (_dataArray) {
                [_dataArray removeAllObjects];
            }else{
                _dataArray = [[NSMutableArray alloc] init];
            }
            _orderModel = [[OrderModel alloc] init];
            _orderModel = [OrderModel objectWithKeyValues:result];
            [_dataArray addObjectsFromArray:_orderModel.data];
            _checkDictionary = [[NSMutableDictionary alloc] init];
            for (int i = 0; i < _dataArray.count; i++) {
                _checkDictionary[[NSString stringWithFormat:@"%d",i]] = [NSNumber numberWithBool:NO];
            }
            [_tableView reloadData];
        }
    }];
}

- (void)creatTableView
{
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 109, ECSCREEN_W, ECSCREEN_H - 109 - 54) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    
    _tableView.tableFooterView = [[UIView alloc]init];
    
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {

        [_tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}


#pragma mark - tableViewNumberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}


#pragma mark - tableViewHeightForRowAtIndexPath
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90.f;
}


#pragma mark - tableViewCellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIButton *button = (UIButton *)[self.view viewWithTag:105];
    if (button.selected) {
        static NSString *reuseIdentifier = @"newCell";
        NewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (nil == cell) {
            NSArray *arr = [[NSBundle mainBundle]loadNibNamed:@"NewCell" owner:nil options:nil];
            for (NSObject *obj in arr) {
                if ([obj isKindOfClass:[NewCell class]]) {
                    cell = (NewCell *)obj;
                    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                        [cell setSeparatorInset:UIEdgeInsetsZero];
                    }
                    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                        [cell setLayoutMargins:UIEdgeInsetsZero];
                    }
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    break;
                }
            }
        }
        [cell setCellWithModel:_dataArray WithIndexPath:indexPath];
        return cell;

    }else{
        static NSString *reuseIdentifier = @"orderCell";
        OrderCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (nil == cell) {
            NSArray *arr = [[NSBundle mainBundle]loadNibNamed:@"OrderCell" owner:nil options:nil];
            for (NSObject *obj in arr) {
                if ([obj isKindOfClass:[OrderCell class]]) {
                    cell = (OrderCell *)obj;
                    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                        [cell setSeparatorInset:UIEdgeInsetsZero];
                    }
                    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                        [cell setLayoutMargins:UIEdgeInsetsZero];
                    }
                    
                    [cell.checkButton addTarget:self action:@selector(checkButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                    
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    break;
                }
            }
        }
        
        cell.checkButton.selected = [_checkDictionary[[NSString stringWithFormat:@"%ld",(long)indexPath.row]] boolValue];
        [cell setCellWithModel:_dataArray WithIndexPath:indexPath];
        return cell;
    }
}


- (void)checkButtonClick:(UIButton*)sender
{
    sender.selected = !sender.isSelected;
    
    UITableViewCell *cell = (UITableViewCell *)sender.superview.superview;
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    
    _checkDictionary[[NSString stringWithFormat:@"%ld",(long)indexPath.row]] = [NSNumber numberWithBool:sender.isSelected];
    
    OrderData *data = _dataArray[indexPath.row];
    [self changeOrderWithModel:data];
}

- (void)changeOrderWithModel:(OrderData *)model
{
    NSDictionary *data = @{
                            @"t_member_Id":_memberModel.member_Id,
                            @"course_Id":model.course_Id,
                            @"status":@"2",
                            };
    
    
    NSDictionary *param = @{
                            @"data":data,
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(UPDATECOURSE) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            if ([result[@"errCode"] integerValue] == 200) {
                
                NSDictionary *data = @{
                                       @"course_Id":model.course_Id,
                                       @"member_Id":model.promulgator_Id,
                                       @"total_price":model.price,
                                       @"coupon_id":@"",
                                       };
                
                NSDictionary *param = @{
                                        @"data":data,
                                        };
                
                [[HttpManager defaultManager] postRequestToUrl:RequestURL(CREATORDER_LP) params:param complete:^(BOOL successed, NSDictionary *result) {
                    if (successed) {
                        if ([result[@"errCode"] integerValue] == 200) {
                            SHOW_ALERT(@"提示", result[@"errMsg"], @"好的", nil, self);
                        }else{
                            SHOW_ALERT(@"提示", result[@"errMsg"], @"好的", nil, nil);
                        }
                    }
                }];
            }else{
                SHOW_ALERT(@"提示", result[@"errMsg"], @"好的", nil, nil);
            }
        }
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self creatSecondHttpRequest];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
